package three;
import java.util.*;

public class A058 {

    //22.括号生成

    StringBuilder path = new StringBuilder();
    List<String> ret = new ArrayList<>();
    int left,right,n;
    public List<String> generateParenthesis(int _n) {
        n=_n;
        dfs();
        return ret;
    }
    public void dfs() {
        //思路：永远是先添加左括号，再添加右括号;并且左括号最多添加n个
        if(right == n) {
            ret.add(path.toString());
            return;
        }
        if(left < n) {
            path.append('(');
            left++;
            dfs();
            //回溯
            path.deleteCharAt(path.length()-1);
            left--;

        }
        //走到这里，说明if进不去或者if回溯出来了
        if(right < left) {  //右括号一定在左括号后面加，所以数量一定是只能小于
            path.append(')');
            right++;
            dfs();
            //回溯
            path.deleteCharAt(path.length()-1);
            right--;
        }
    }
}
